package cn.school.mybatis.service;

import cn.school.mybatis.dao.StudentDao;
import cn.school.mybatis.pojo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

//业务逻辑bean
//服务层,调用dao方法
@Service
//@Transactional(readOnly = false)
public class StudentService {
    @Autowired
    private StudentDao studentDao ;
    //模糊查tel数量
    public boolean findTel(String tel) {
        Map map = new HashMap<>();
        map.put("telephone", tel);
        return this.findTotal(map) > 0;
    }

    //模糊查weixin数量
    public boolean findWechat(String wechat) {
        Map map = new HashMap<>();
        map.put("wechat", wechat);
        return this.findTotal(map) > 0;
    }

    //增加
//    @Transactional(readOnly = false)
    public int add(Student student) {
        return studentDao.add(student);
    }

    //删除
    public int delete(int stuno) {
        return studentDao.delete(stuno);
    }

    //修改
    public int update(Student student) throws Exception {
        return studentDao.update(student);
    }

    //修改分数
//    @Transactional(readOnly = false,rollbackFor = {Exception.class})
    public int updateScore(Student student) throws Exception {
        //更新时给他涨5分
        int r=studentDao.update(student);
        int r2=0;
        if (r2 < 1) {
            throw new Exception("此人未参加考试，不得修改信息！");
        }
        return r;
    }

    //查单个
    public Student get(int stuno) {
//        studentDao = SpringMButil.getBean(StudentDao.class);
        return studentDao.get(stuno);
    }

    //模糊查数量
    public int findTotal(Map map) {
        return studentDao.findTotal(map);
    }

    //模糊分页查询
    public List<Student> search(int pageNo, int pageSize, Map<String, Object> condition) {
        int offset = (pageNo - 1) * pageSize;
        offset = Math.max(offset, 0);
        Map<String, Object> map = new HashMap<>();
        map.put("pageNo", offset);
        map.put("pageSize", pageSize);
        map.put("orderBy", "stuno asc");
        if (condition.size() > 0) {
            for (String key : condition.keySet()) {
                map.put(key, condition.get(key));
            }
        }
        List<Student> list = studentDao.search(map);
        return list;

    }

}
